package com.stormrage.edu.ctrl.index;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.index.IdxGuideServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.index.IdxGuide;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.exception.StormrageTechException;

/**
 * @Title: IdxGuideCtrl.java
 * @Package com.stormrage.edu.ctrl.index
 * @Description: 用户指南 Controller
 * @author www.stormragetech.com
 * @date 2016年4月22日
 * @version V1.0
 */
@Controller
@RequestMapping("/idx/guide")
public class IdxGuideCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(IdxImageCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['path.root']}")
	private String rootPath;

	@Value("#{constants['url.root']}")
	private String rootUrl;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Value("#{constants['path.ckeditor']}")
	private String ckeditorPath;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private IdxGuideServ idxGuideServ;

	@RequiresPermissions("guide:edit")
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 IdxTrialCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			IdxGuide entity = idxGuideServ.queryGuide();

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 IdxTrialCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "index/guide/edit";

	}

	@RequiresPermissions("trial:edit")
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, IdxGuide req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 IdxTrialCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		logger.debug(" edit请求为 " + req.toString());

		try {

			// ------------------ Ctrl操作 ------------------
			idxGuideServ.update(req);
			errMsg = "提示信息：修改用户指南成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改用户指南失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/idx/guide/edit";
		}

		logger.debug(" 【 Controller 】-【 IdxTrialCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/idx/guide/edit";

	}

	@RequiresPermissions("guide:edit")
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@CurrentUser ShiroAcct curr,
			@RequestParam(value = "upload", required = false) MultipartFile file, HttpServletRequest request,
			HttpServletResponse response, @RequestParam("CKEditorFuncNum") String callback) throws IOException {

		logger.debug(" 【 Controller 】-【 IdxTrialCtrl 】-【 Upload 】-【 POST 】- 开始运行 ");

		try {

			PrintWriter out = response.getWriter();

			if (null == file) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "上传文件不能为空",
						StormrageTechException.ERR_APP, "【 EduProjectCtrl 】-【 Upload 】");

				out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'"
						+ exception.getMessage() + "');");
				out.println("</script>");
				return null;
			}

			// ------------------ 上传图片操作 ------------------

			String path = rootPath + ckeditorPath;
			String url = rootUrl + ckeditorPath + File.separator;
			String fileName = idxGuideServ.upload(file, path);
			out.println("<script type=\"text/javascript\">");
			out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + url + fileName + "','')");
			out.println("</script>");

		} catch (Exception e) {
			PrintWriter out = response.getWriter();
			out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'CKEditor上传图片失败');");
			out.println("</script>");
			return null;
		}

		logger.debug(" 【 Controller 】-【 IdxTrialCtrl 】-【 Upload 】-【 POST 】- 结束运行 ");
		return null;
	}

}
